<?php

namespace AgilePayments\Union;

use AgilePayments\Extend\Union\AcpService;
use AgilePayments\Extend\Union\SDKConfig;
use AgilePayments\Config;
use AgilePayments\Tool;
use fast\Random;

class Service
{
    private $config;
    
    public function __construct(Config $config)
    {
        $this->config = $config;
    }

    /**
     * 支付
     * @param string $order_no
     * @param string $pay_price
     * @param string $out_time
     * @param string $notify_url
     * @param array  $extra_param
     * @param string $title
     * @return void
     */
    public function pay($order_no, $pay_price, $out_time, $notify_url, $extra_param, $title = '')
    {
        $params = array(
            //以下信息非特殊情况不需要改动
            'version'       => '5.1.0',
            'encoding'      => 'utf-8',
            'txnType'       => '01',
            'txnSubType'    => '01',
            'bizType'       => '000201',
            'frontUrl'      => 'http://localhost:8086/upacp_demo_app/demo/api_05_app/FrontReceive.php',
            'backUrl'       => $notify_url,
            'signMethod'    => '01',
            'channelType'   => '08',
            'accessType'    => '0',
            'currencyCode'  => '156',
            'payTimeout'    => date('YmdHis',$out_time),
            'merId'         => $this->config->pay_type_config->mid,
            'reqReserved'   => json_encode($extra_param),
            'orderId'       => $order_no,
            'txnTime'       => date('YmdHis'),
            'txnAmt'        => $pay_price,
        );
        AcpService::sign($params);

        $url = SDKConfig::getSDKConfig()->appTransUrl;
        Tool::log($params);
        $result_arr = AcpService::post ($params,$url);
        Tool::log($result_arr);
        if ($result_arr["respCode"] == "00"){
            return ['status' => true, 'msg'=>$result_arr["respMsg"], 'data'=>['appPayRequest'=>['tn'=>$result_arr["tn"]],'pay_type'=>$this->config->pay_type],'time'=>time()];
        } else {
            return ['status' => false, 'msg'=>$result_arr["respMsg"], 'data'=>['appPayRequest'=>['tn'=>''],'pay_type'=>$this->config->pay_type],'time'=>time()];
        }
    }

    public function verifySign($request)
    {

        $status = AcpService::validate($_POST);
        if ($status){
            $status = true;
        }else{
            $status = false;
        }
        return [
            'status'        => $status,
            'payOrderId'    => $_POST['orderId']??'',
            'trade_no'      => $_POST['traceNo']??'',
            'query_id'      => $_POST['queryId']??'',
            'data'          => $_POST??[],
        ];
    }


    public function refund($payInfo, $notify = '')
    {
        $params = array(
            //以下信息非特殊情况不需要改动
            'version'       => SDKConfig::getSDKConfig()->version,                 //版本号
            'encoding'      => 'utf-8',				  //编码方式
            'signMethod'    => SDKConfig::getSDKConfig()->signMethod,	              //签名方法
            'txnType'       => '04',				      //交易类型
            'txnSubType'    => '00',				  //交易子类
            'bizType'       => '000201',				  //业务类型
            'accessType'    => '0',		          //接入类型
            'channelType'   => '08',	              //渠道类型，07-PC，08-手机
            'merId'         => $this->config->pay_type_config->mid,
            'orderId'       => $payInfo['out_order_id'] . time(),
            'origQryId'     => $payInfo['query_id'],
            'txnTime'       => date('YmdHis'),
            'txnAmt'        => $payInfo['pay_amount'],	//交易金额，单位分
            'backUrl'       => $_SERVER['HTTP_HOST'],	  //后台通知地址
//            'reqReserved'   => json_encode($this->reqReserved), // ??
        );
        AcpService::sign($params);

        $url = SDKConfig::getSDKConfig()->backTransUrl;
        $result_arr = AcpService::post ($params,$url);
        if ($result_arr["respCode"] == "00"){
            return ['status'=>true, 'msg'=>$result_arr['respMsg'],'data'=>$result_arr];
        } else {
            return ['status'=>false, 'msg'=>$result_arr['respMsg'],'data'=>$result_arr];
        }
    }

    /**
     * @deac 退款查询（银联没有退款状态查询，查询支付状态取代）
     */
    public function refundQuery($refund_no, $trade_no, $date = '')
    {
        $params = array(
            //以下信息非特殊情况不需要改动
            'version'       => SDKConfig::getSDKConfig()->version,                 //版本号
            'encoding'      => 'utf-8',				  //编码方式
            'signMethod'    => SDKConfig::getSDKConfig()->signMethod,	              //签名方法
            'txnType'       => '00',				      //交易类型
            'txnSubType'    => '00',				  //交易子类
            'bizType'       => '000201',				  //业务类型
            'accessType'    => '0',		          //接入类型
            'merId'         => $this->config->pay_type_config->mid,
            'orderId'       => $refund_no,
            'txnTime'       => $date,
        );
        AcpService::sign($params);

        $url = SDKConfig::getSDKConfig()->singleQueryUrl;
        $result_arr = AcpService::post ($params,$url);
        if ($result_arr["respCode"] == "00"){
            return [
                'status'    => true,
                'msg'       => $result_arr['respMsg'],
                'data'      => $result_arr??[]
            ];
        } else {
            return [
                'status'    => false,
                'msg'       => $result_arr['respMsg'],
                'data'      => $result_arr??[]
            ];
        }
    }

    public function query($trade_no, $date)
    {
        $params = array(
            //以下信息非特殊情况不需要改动
            'version'       => SDKConfig::getSDKConfig()->version,                 //版本号
            'encoding'      => 'utf-8',				  //编码方式
            'signMethod'    => SDKConfig::getSDKConfig()->signMethod,	              //签名方法
            'txnType'       => '00',				      //交易类型
            'txnSubType'    => '00',				  //交易子类
            'bizType'       => '000201',				  //业务类型
            'accessType'    => '0',		          //接入类型
            'merId'         => $this->config->pay_type_config->mid,
            'orderId'       => $trade_no,
            'txnTime'       => $date,
        );
        AcpService::sign($params);

        $url = SDKConfig::getSDKConfig()->singleQueryUrl;
        $result_arr = AcpService::post ($params,$url);
        if ($result_arr["respCode"] == "00"){
            return [
                'status'    => true,
                'msg'       => $result_arr['respMsg'],
                'data'      => $result_arr??[]
            ];
        } else {
            return [
                'status'    => false,
                'msg'       => $result_arr['respMsg'],
                'data'      => $result_arr??[]
            ];
        }
    }

    public function returnSuccess()
    {
        echo "SUCCESS";
    }

}